package com.qzboot.backend.web.common;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;

import java.io.IOException;
import java.util.List;

/**
 * @author zengzhihong
 * @date 2019-12-18
 */
@Slf4j
public class Ip2Region {

    private static final char SEPARATOR = '|';

    public static DbSearcher REGION_SEARCHER = null;

    static {
        try {
            REGION_SEARCHER = new DbSearcher(new DbConfig(),ResourceUtil.readBytes("other/ip2region.db"));
        } catch (Exception e) {
            log.error("IP地址库初始化异常", e);
        }
    }

    public static String getRegion(String ip) {
        if (StrUtil.isBlank(ip)) {
            return null;
        }
        DataBlock dataBlock;
        try {
            dataBlock = REGION_SEARCHER.memorySearch(ip);
        } catch (IOException e) {
            log.error("getRegion error", e);
            return null;
        }
        if (null == dataBlock) {
            return null;
        }
        if (StrUtil.isBlank(dataBlock.getRegion())) {
            return null;
        }
        if (StrUtil.indexOf(dataBlock.getRegion(), SEPARATOR) < 0) {

        }
        List<String> regionSplit = StrUtil.split(dataBlock.getRegion(), SEPARATOR);
        if (CollectionUtil.isNotEmpty(regionSplit) && regionSplit.size() > 2) {
            for (int i = 0; i < 2; i++) {
                regionSplit.remove(0);
            }
            return CollectionUtil.join(regionSplit, StrUtil.EMPTY);
        }
        return null;
    }

    public static void main(String[] args) {
        String region = Ip2Region.getRegion("218.66.216.142");
        System.out.println(region);
        String path = ResourceUtil.getResource("other/ip2region.db").getPath();
        System.out.println(path);
    }
}
